package com.xiaobai.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.UUID;


@Component
@Slf4j
public class OnceTokenGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory{

    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return (exchange, chain) -> chain.filter(exchange).then(Mono.fromRunnable(()->{
            ServerHttpResponse response = exchange.getResponse();
            HttpHeaders headers = response.getHeaders();
            String value = config.getValue();
            if ("uuid".equals(value)){
                value = UUID.randomUUID().toString();
            }
            if ("jwt".equals(value)){
                value = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyMTIzIiwiaWF0IjoxNjc1NzYxMjAwLCJleHAiOjE2NzU3NjQ4MDAsInJvbGUiOiJhZG1pbiJ9.5BkT2K0GzVwvXZG8RlX0J6Q2aJZ5J8FV3G2QYJ6Y0jw";
            }
            headers.add(config.getName(),value);
        }));
    }
}
